<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :okButtonProps="{ props: {disabled: disableSubmit} }"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="等级id"
          :hidden="hiding"
          hasFeedback>
          <a-input placeholder="请输入等级id" v-decorator="['levelId', {'initialValue':this.mainId}]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="广告图片"
          hasFeedback>
          <a-upload
            listType="picture-card"
            class="logo-uploader"
            :showUploadList="false"
            :action="uploadAction"
            :data="{'isup':1,'dir':'cms/level/banner'}"
            :headers="headers"
            :beforeUpload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="picUrl" :src="getLogoView()" alt="logo" style="height:104px;max-width:300px"/>
            <div v-else>
              <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="广告链接"
          hasFeedback>
<!--          <a-input placeholder="请输入广告链接" v-decorator="['link', {}]"/>-->
          <j-dict-select-tag v-model="bannerType" placeholder="广告跳转类型" type="radioButton"
                              dictCode="member_level_banner_type"/>
          <a-input v-model="id" :hidden="this.bannerType =='none' || this.bannerType =='home' || this.bannerType =='url' "/>
          <a-input v-model="href" :hidden="this.bannerType !=='url' "/>
        </a-form-item>

      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import { httpAction } from '@/api/manage'
import pick from 'lodash.pick'
import moment from 'moment'
import JDate from '@/components/jeecg/JDate'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import Vue from 'vue'

export default {
  components: {
    JDate
  },
  name: 'UmsMemberLevelBannerModal',
  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      moment,
      format: 'YYYY-MM-DD HH:mm:ss',
      disableSubmit: false,
      mainId: '',
      hiding: false,
      confirmLoading: false,
      uploadLoading:false,
      headers:{},
      bannerType: "",
      id: "",
      href: "",
      link: {},
      form: this.$form.createForm(this),
      validatorRules: {},
      picUrl: "",
      url: {
        add: '/ums/umsMemberLevel/addUmsMemberLevelBanner',
        edit: '/ums/umsMemberLevel/editUmsMemberLevelBanner',
        fileUpload: window._CONFIG['domianURL']+"/sys/common/ossUpload",
        imgerver: window._CONFIG['domianURL']+"/sys/common/view",
      }
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN);
    this.headers = {"X-Access-Token":token};
  },
  computed:{
    uploadAction:function () {
      return this.url.fileUpload;
    }
  },
  methods: {
    add(mainId) {
      if (mainId) {
        this.picUrl = "";
        this.edit({ mainId }, '')
      } else {
        this.$message.warning('请选择一条数据')
      }
    },
    detail(record) {
      this.edit(record, 'd')
    },
    edit(record, v) {
      if (v == 'e') {
        this.hiding = false
        this.disableSubmit = false
      } else if (v == 'd') {
        this.hiding = false
        this.disableSubmit = true
      } else {
        this.hiding = true
        this.disableSubmit = false
      }
      this.form.resetFields()
      this.mainId = record.mainId
      this.model = Object.assign({}, record)
      this.picUrl = this.model.pic;
      if(this.model.link) {
        this.link = JSON.parse(this.model.link);
        this.bannerType = this.link.type;
        this.id = this.link.id;
        this.href = this.link.href;
      }
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'levelId', 'pic'))
        // 时间格式化
      })
    },
    beforeUpload: function(file){
      var fileType = file.type;
      if(fileType.indexOf('image')<0){
        this.$message.warning('请上传图片');
        return false;
      }
      //TODO 验证文件大小
    },
    handleChange (info) {
      this.picUrl = "";
      if (info.file.status === 'uploading') {
        this.uploadLoading = true;
        return
      }
      if (info.file.status === 'done') {
        var response = info.file.response;
        this.uploadLoading = false;
        console.log(response);
        if(response.success){
          this.model.pic = response.message;
          this.picUrl = this.model.pic;
        }else{
          this.$message.warning(response.message);
        }
      }
    },
    getLogoView(){
      if(this.model.pic !== null && this.model.pic !== undefined && this.model.pic !== ''){
        if('http' === this.model.pic.substring(0,4)){
          return this.model.pic;
        }
        return this.url.imgerver +"/"+ this.model.pic;
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          if (this.bannerType =='none' || this.bannerType =='home') {
            this.link = {type : this.bannerType}
          } else if (this.bannerType =='url') {
            this.link = {type : this.bannerType, href :this.href};
          } else {
            this.link = {type : this.bannerType, id :this.id};
          }

          let formData = Object.assign(this.model, values)
          formData.link = JSON.stringify(this.link);
          //时间格式化
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })
        }
      })
    },
    handleCancel() {
      this.close()
    }
  }
}
</script>

<style scoped>

</style>
